﻿// ----------------------------------------------------------------------------------
// Sample Code from Fernando Machado Píriz's blog: http://fernandomachadopiriz.com
//
// <copyright company="Fernando Machado Píriz"  file="SingleInstanceApplication.cs">
// Copyright (c) Fernando Machado Píriz. Distributed under FSF's GPL v2.</copyright>
// ----------------------------------------------------------------------------------
// This code and information are provided "as is" without warranty of any kind,
// either expressed of implied, including but not limited to the implied warranties
// of merchantability and/or fitness for a particular purpose.
// ----------------------------------------------------------------------------------
namespace GivingAPresentation
{
    using System;
    using System.Windows;
    using GivingAPresentation.Commons;

    /// <summary>
    /// Logic for the application of which only one instance is allowed. The first instance runs normally but remaining instances just
    /// activates the first instance and then stop.
    /// </summary>
    public sealed class SingleInstanceApplication : Application
    {
        /// <summary>
        /// Launches the application in the mode indicated by the command-line arguments if this is the first instance:
        ///   start: automatically starts a presentation.
        ///   stop: automatically stops a presentation.
        ///   add: adds commands to the jump list in Windows 7.
        ///   remove: removes commands from the jump list in Windows 7.
        /// <para/>
        /// Activates a previous instance if this is not the first instance.
        /// </summary>
        /// <param name="args">The command-line arguments used to call this application.</param>
        /// <param name="firstInstance">A value indicating if this is the first instance of the application or not.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0",
            Justification = "Argument is validated by using ExceptionHelper.CheckArgumentNotNull")]
        public void ProcessArgs(string[] args, bool firstInstance)
        {
            ExceptionHelper.CheckArgumentNotNull(args, "args");

            MainViewModel viewModel = null;
            MainModel model = null;

            viewModel = MainWindow.Resources["viewModel"] as MainViewModel;
            if (viewModel != null)
            {
                model = viewModel.Model;
            }

            if (firstInstance && args.Length == 0)
            {
                MainWindow.Show();
            }
            else if (!firstInstance && args.Length == 0)
            {
                this.RestoreMainWindow();
            }
            else if (args.Length > 0 && model != null && args[0].Equals("start", StringComparison.OrdinalIgnoreCase) && !model.Presenting)
            {
                MainWindow.Show();
                model.Presenting = true;
            }
            else if (args.Length > 0 && model != null && args[0].Equals("stop", StringComparison.OrdinalIgnoreCase) && model.Presenting)
            {
                MainWindow.Show();
                model.Presenting = false;
            }
            else
            {
                this.RestoreMainWindow();
            }
        }

        /// <summary>
        /// Called when the first instance of the application is run. Creates the main window passing command-line arguments for
        /// processing.
        /// </summary>
        /// <param name="e">Contains the command-line arguments used to call the application.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0",
            Justification = "The call to ExceptionHelper.CheckArgumentNotNull is validating the argument")]
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            ExceptionHelper.CheckArgumentNotNull(e, "e");

            MainWindow = new MainView();
            this.ProcessArgs(e.Args, true);
        }

        /// <summary>
        /// Restores the main window of this applicatoin.
        /// </summary>
        private void RestoreMainWindow()
        {
            if (!MainWindow.IsVisible)
            {
                MainWindow.Show();
            }

            if (MainWindow.WindowState != WindowState.Normal)
            {
                MainWindow.WindowState = WindowState.Normal;
            }
        }
    }
}
